<script setup>
import {
  DeleteOutlined,
  EditOutlined,
  LinkOutlined,
  CloudUploadOutlined,
  ExclamationCircleOutlined,
} from "@ant-design/icons-vue";
import {
  theme,
  message,
  Typography,
  Button,
  Flex,
  Modal,
} from "ant-design-vue";
import {
  Conversations,
  Welcome,
  Sender,
  Bubble,
  Attachments,
} from "ant-design-x-vue";
import { computed, h, nextTick, onMounted, ref, createVNode } from "vue";
import markdownit from "markdown-it";

const md = markdownit({ html: true, breaks: true });
const { token } = theme.useToken();

// 从url中获取参数
const params = new URLSearchParams(window.location.search);
const clientId =
  params.get("clientId") || "1887323151002415104681832717175751429";
const userId = params.get("userId") || "681832717175751429";
const tenantId = params.get("tenantId") || "1887323151002415104";

const reqUrl = "http://192.168.8.90:8080";

// 样式处理
const headerStyle = {
  height: "82px",
  background: "#f5f5f5",
  padding: "0px",
};
const contentStyle = ref({
  height: "calc(100vh - 82px - 146px)",
  display: "flex",
  justifyContent: "center",
  background: "#f5f5f5",
});

const siderStyle = {
  textAlign: "center",
  background: "#FFF",
};
const footerStyle = {
  maxHeight: "252px",
  minHeight: "146px",
};

//#region 侧边栏对话记录
const items = Array.from({ length: 1 }).map((_, index) => ({
  key: `item${index + 1}`,
  label: `销采云客户操作`,
}));

const style = computed(() => ({
  width: "256px",
  background: token.value.colorBgContainer,
  borderRadius: token.value.borderRadius,
}));

const menuConfig = (conversation) => ({
  items: [
    {
      label: "编辑",
      key: "编辑",
      icon: h(EditOutlined),
    },
    {
      label: "删除",
      key: "删除",
      icon: h(DeleteOutlined),
      danger: true,
    },
  ],
  onClick: (menuInfo) => {
    message.info(`点击了${menuInfo.key}按钮`);
  },
});
//#endregion

// 新增对话记录相关代码
const conversationHistory = ref([]);

const userInput = ref("");
const contentContain = ref(null);

const senderLoading = ref(false);

// 修改submit函数以处理对话记录
const submit = async (question) => {
  if (!question.trim()) return;

  // 添加用户消息
  conversationHistory.value.push({
    messageType: "user",
    content: question,
    timestamp: new Date(),
  });

  userInput.value = "";

  senderLoading.value = true;

  try {
    const formData = new FormData();
    formData.append("question", question);
    formData.append("clientId", clientId);
    // 添加文件（如果有）
    const file = fileItems.value[0]?.originFileObj;
    if (file) {
      formData.append("file", file);
    }

    const response = await fetch(reqUrl + "/ask", {
      method: "POST",
      body: formData,
    });

    const answer = await response.text();

    // 添加AI回复
    conversationHistory.value.push({
      messageType: "assistant",
      content: answer,
      timestamp: new Date(),
      newMessage: true,
    });

    await nextTick();
    if (contentContain.value) {
      contentContain.value.scrollTop = contentContain.value.scrollHeight;
    }
  } catch (error) {
    message.error("获取回复失败");
    console.error(error);
  } finally {
    senderLoading.value = false;
  }
};

const getConversationHistory = async () => {
  const response = await fetch(
    `${reqUrl}/history?clientId=${clientId}&size=99`
  );
  const res = await response.json();
  conversationHistory.value = res.map((item) => {
    return {
      messageType: item.messageType,
      content: item.text,
      timestamp: new Date(),
      newMessage: false,
    };
  });

  // 滚动到最新消息
  nextTick(() => {
    if (!contentContain.value) return;
    contentContain.value.scrollTop = contentContain.value.scrollHeight;
  });
};

const renderMarkdown = (content) =>
  h(Typography, null, {
    default: () => h("div", { innerHTML: md.render(content) }),
  });

// 会话历史记录相关
const historicalRecord = ref([]);
const getHistoryRecord = async () => {
  const response = await fetch(
    `${reqUrl}/history?clientId=${clientId}&size=99`
  );
  const res = await response.json();
  historicalRecord.value = res.data;
};

onMounted(() => {
  // getHistoryRecord()
  getConversationHistory();
});

//文件相关处理
const open = ref(false);
const attachmentsRef = ref(null);
const fileItems = ref([]);

const fileChange = ({ file, fileList }) => {
  if (file.size > 1024 * 1024 * 10) {
    message.error("文件大小超过10MB");
    return;
  }
  fileItems.value = fileList;
};

const placeholder = (type) =>
  type === "drop"
    ? {
        title: "Drop file here",
      }
    : {
        icon: h(CloudUploadOutlined),
        title: "Upload files",
        description: "Click or drag files to this area to upload",
      };

// 拖拽上传支持
const senderRef = ref(null);
const getDropContainer = () => senderRef.value?.nativeElement;

const clearHistoricalMessages = async () => {
  Modal.confirm({
    title: "清空对话",
    icon: createVNode(ExclamationCircleOutlined),
    content: "本次对话将被清空，是否继续？",
    okText: "继续",
    cancelText: "取消",
    onOk: async () => {
      // 乐观更新UI
      conversationHistory.value = [];
      userInput.value = "";
      message.success("清空成功");

      fetch(`${reqUrl}/aiLogin`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          clientId: clientId,
          userId: userId,
          tenantId: tenantId,
        }),
      });
    },
  });
};

const modalVisible = ref(false);

const handleAIClick = () => {
  console.log("AI助理");
  modalVisible.value = !modalVisible.value;
};
</script>

<template>
  <a-modal
    v-model:visible="modalVisible"
    :footer="null"
    :width="500"
    :bodyStyle="{ padding: '0' }"
    :maskStyle="{ backgroundColor: 'rgba(0, 0, 0, 0.45)' }"
    :style="{ top: '20px',padding: '0' }"
  >
    <div class="ai-chat-container">
      <a-layout>
        <a-layout-sider :style="siderStyle" width="256px" v-if="false">
          <Conversations
            default-active-key="item1"
            :menu="menuConfig"
            :items="items"
            :style="style"
          />
        </a-layout-sider>
        <a-layout>
          <a-layout-header :style="headerStyle">
            <Welcome
              icon="https://www.huangxi.cc/deepseekIcon.png"
              title="我是即刻AI，很高兴见到你！"
              description="能够基于你的指示，完成业务流程的控制~"
            />
          </a-layout-header>
          <a-layout-content :style="contentStyle">
            <WelcomeIndex v-if="!conversationHistory.length" class="mb-4" />
            <div
              v-else
              ref="contentContain"
              style="width: 100%; height: 100%; overflow-y: auto; padding: 20px"
            >
              <div
                v-for="(message, index) in conversationHistory"
                :key="index"
                :style="{
                  display: 'flex',
                  justifyContent:
                    message.messageType === 'user' ? 'flex-end' : 'flex-start',
                  marginBottom: '16px',
                }"
              >
                <Bubble
                  :typing="message.newMessage ? true : false"
                  :content="message.content"
                  :messageRender="renderMarkdown"
                  :variant="
                    message.messageType === 'user' ? 'filled' : 'outlined'
                  "
                  :style="{
                    maxWidth: '100%',
                    backgroundColor:
                      message.messageType === 'user' ? '' : '#f6f6f6',
                    borderRadius:
                      message.messageType === 'user'
                        ? '18px 18px 0 18px'
                        : '18px 18px 18px 0',
                    padding: '12px 16px',
                  }"
                />
              </div>
            </div>
          </a-layout-content>
          <a-layout-footer :style="footerStyle">
            <Flex :style="{ maxHeight: '252px' }" align="end">
              <Sender
                v-model:value="userInput"
                :loading="senderLoading"
                :allow-speech="true"
                @submit="submit"
                @cancel="senderLoading = false"
                placeholder="给即刻AI发送消息"
              >
                <template #prefix>
                  <Button
                    type="text"
                    :icon="h(LinkOutlined)"
                    @click="
                      () => {
                        open = !open;
                        contentStyle.height = open
                          ? 'calc(100vh - 82px - 146px - 158px)'
                          : 'calc(100vh - 82px - 146px)';
                      }
                    "
                  />
                </template>
                <template #header>
                  <Sender.Header
                    title="文件"
                    :styles="{
                      content: {
                        padding: 0,
                      },
                    }"
                    :open="open"
                    :on-open-change="(v) => (open = v)"
                    force-render
                  >
                    <Attachments
                      ref="attachmentsRef"
                      :items="fileItems"
                      :on-change="fileChange"
                      :placeholder="placeholder"
                      :get-drop-container="getDropContainer"
                    />
                  </Sender.Header>
                </template>
              </Sender>
            </Flex>
            <div
              style="
                margin-top: 10px;
                color: gray;
                display: flex;
                justify-content: space-between;
              "
            >
              <span>AI 也可能会犯错，请核查重要信息。</span>
              <Button type="link" danger @click="clearHistoricalMessages"
                >清空对话</Button
              >
            </div>
          </a-layout-footer>
        </a-layout>
      </a-layout>
    </div>
  </a-modal>

  <div class="fixedAI" @click="handleAIClick">
    <div class="fixedAIIcon">
      <img
        class="fixedAIImg"
        src="https://img.alicdn.com/imgextra/i2/O1CN01bYc1m81RrcSAyOjMu_!!6000000002165-54-tps-60-60.apng"
      />
    </div>
    <div class="laarvw">AI助理</div>
  </div>
</template>

<style scoped>
.ai-chat-container {
  width: 100%;
  background: #f5f5f5;
}

.fixedAI {
  position: fixed;
  right: 20px;
  bottom: 40px;
  width: 36px;
  height: 100px;
  z-index: 9999;
  background: rgb(255, 255, 255);
  border-radius: 36px 36px 36px 36px;
  color: rgb(24, 24, 24);
  display: flex;
  flex-direction: column;
  align-items: center;
  user-select: none;
  cursor: pointer;
}

.fixedAIIcon {
  width: 26px;
  height: 26px;
  margin-top: 5px;
  margin-bottom: 6px;
  background: url("https://img.alicdn.com/imgextra/i4/O1CN012X1Rxl1clAgB5waMK_!!6000000003640-2-tps-52-52.png")
    center center / 100% no-repeat;
  position: relative;
}

.fixedAIImg {
  position: absolute;
  width: 100%;
}

.laarvw {
  width: 14px;
  margin: 0px auto auto;
  display: block;
  font-size: 14px;
  line-height: 16px;
  font-weight: 500;
}


</style>
